package cn.edu.dyxy.dao;

import cn.edu.dyxy.entity.TAddress;
import cn.edu.dyxy.entity.TOrder;
import cn.edu.dyxy.entity.TOrderItem;
import cn.edu.dyxy.utils.DBUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @author JokerQiu
 * @date 2021年12月25日 14:23
 */

public class OrderDao {
    /**
     * 创建订单
     *
     * @param address
     * @param order
     * @param orderItems
     * @return
     */
    public TOrder createOrder(TAddress address, TOrder order,
                              List<TOrderItem> orderItems) throws SQLException {
        Connection connection = DBUtils.getConntect();
        connection.setAutoCommit(false);//关闭自动提交
        //插入地址信息
        String sql = "insert into t_address(user_id,receive_name,full_address,postal_code,mobile,phone) values (?,?,?,?,?,?)";
        PreparedStatement ps1 = connection.prepareStatement(sql);
        ps1.setInt(1, address.getUserId());
        ps1.setString(2, address.getReceiveName());
        ps1.setString(3, address.getFullAddress());
        ps1.setString(4, address.getPostalCode());
        ps1.setString(5, address.getMobile());
        ps1.setString(6, address.getPhone());
        ps1.executeUpdate();

        //插入订单信息
        String orderSql = "insert into t_order(user_id,order_time,order_desc,total_price) values(?,?,?,?)";
        PreparedStatement ps2 = connection.prepareStatement(orderSql, PreparedStatement.RETURN_GENERATED_KEYS);
        ps2.setInt(1, order.getUserId());
        ps2.setString(2, order.getOrderTime());
        ps2.setString(3, order.getOrderDesc());
        ps2.setDouble(4, order.getTotalPrice());
        ps2.executeUpdate();
        ResultSet resultSet = ps2.getGeneratedKeys();
        int orderId = 0;
        if (resultSet.next()) {
            orderId = resultSet.getInt(1);
        }
        //为订单设置id
        order.setId(orderId);

        //插入订单子表
        String sql2 = "insert into t_order_item(order_id,book_id,book_name,dang_price,book_num,amount) values(?,?,?,?,?,?)";
        PreparedStatement ps3 = connection.prepareStatement(sql2);
        for (TOrderItem orderItem : orderItems) {
            ps3.setInt(1, orderItem.getOrderId());
            ps3.setInt(2, orderItem.getBookId());
            ps3.setString(3, orderItem.getBookName());
            ps3.setDouble(4, orderItem.getDangPrice());
            ps3.setInt(5, orderItem.getBookNum());
            ps3.setDouble(6, orderItem.getAmount());
            ps3.executeUpdate();
        }
        //手动提交
        connection.commit();
        //关闭连接
        ps1.close();
        ps2.close();
        ps3.close();
        connection.close();
        return order;
    }
}
